package org.kl.wx.web;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.mp.api.WxMpService;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.utils.ExcelWriter;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.kl.wx.entity.App;
import org.kl.wx.entity.WxLocolMenu;
import org.kl.wx.service.AppService;
import org.kl.wx.service.WxMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

@Controller
@RequestMapping(value = "/wx/wxMenu")
public class WxMenuController extends BasicController {
	@Autowired
	private WxMenuService menuService;
	@Autowired
	private AppService appService;

	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "/wx/wxMenuList";
	}

	@RequiresPermissions("menu:list")
	@RequestMapping(value = "/treeGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String treeGrid() {
		String result = jsonMapper.toJson(menuService.treeGrid());
		return result;
	}

	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("menu") WxLocolMenu menu, BindingResult result, HttpSession session) {
		if (result.hasErrors()) {
			System.out.println(result);
			return ajaxMsg(bindingMsg(result), false, null);
		}
		if (menu.getOauthState() != BasicConstants.NO_INT) {
			App app = appService.getApp(menu.getApp().getId());
			app.setOauth2redirectUri(BasicConstants.SYSTOM_URL + "/wxWeb/wxWebBasic?appid=" + app.getOriginAppId());
			WxMpService wxMpService = super.getWxMpServiceByAppId(session, app.getOriginAppId());
			wxMpService.setWxMpConfigStorage(app);
			menu.setMenuUrl(wxMpService.oauth2buildAuthorizationUrl("snsapi_base", menu.getStateName()));
		}
		try {
			menuService.saveMenu2(menu);
			return ajaxMsg("保存成功", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("保存失败" + e.getMessage(), false, null);
		}
	}

	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			menuService.deleteMenu(id);
			return ajaxMsg("删除成功", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败", false, null);
		}
	}

	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = menuService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	// 同步微信菜单
	@RequestMapping(value = "synMenu", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String synMenu(@RequestParam(value = "appId", defaultValue = "") String appId, HttpSession session) {
		try {
			WxMpService wxMpService = super.getWxMpServiceByAppId(session, appId);
			WxMenu wxMenu = (WxMenu) wxMpService.menuGet();
			menuService.getMenu(wxMpService, wxMenu, appId);
			return ajaxMsg("同步成功", true, wxMenu);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("同步失败", false, null);
		}
	}

	// 更新微信服务器菜单
	@RequestMapping(value = "updateMenu", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String updateMenu(@RequestParam(value = "originAppId", defaultValue = "") String originAppId,
			@RequestParam(value = "appId", defaultValue = "") String appId, HttpSession session) {
		try {
			WxMpService wxMpService = super.getWxMpServiceByAppId(session, originAppId);
			menuService.updateMenu(wxMpService, appId);
			return ajaxMsg("同步更新成功", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("同步更新失败", false, null);
		}
	}

	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<WxLocolMenu> menu = menuService.getMenu(searchParams, pageNumber, 0, sortType, orderType);
		try {
			// 输出Excel文件.
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment;filename=\""
							+ new String(("微信菜单" + new DateTime().toString("yyyyMMddHHmmss") + ".xls").getBytes("gb2312"), "ISO8859-1")
							+ "\"");
			ExcelWriter.exportExcel("微信菜单", WxLocolMenu.class, menu.getContent(), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@ModelAttribute
	public void getMenu(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("menu", menuService.getMenu(id));
		}
	}
}
